package com.starmark.gateway.auth.security.service.impl;


import com.starmark.gateway.auth.security.config.GatewayProjectConfig;
import com.starmark.gateway.auth.security.service.IJwtTokenService;
import com.starmark.gateway.auth.security.utils.JwtHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * @author starmark
 * @date 20-1-23  下午10:08
 */
@Service("jwtTokenService")
public class JwtTokenServiceImpl implements IJwtTokenService {

    @Autowired
    private JwtHelper jwtHelper;
    @Autowired
    private GatewayProjectConfig gatewayProjectDto;

    @Override
    public String createJwtToken(String userInfo, String salt, long expireTime) {
        return jwtHelper.sign(userInfo, salt, expireTime);
    }

    @Override
    public String createJwtToken(String token, String projectCode) {

        return this.createJwtToken(token, gatewayProjectDto.getSalt(), gatewayProjectDto.getExpireTime());
    }

    @Override
    public String getUserInfoByJwtToken(String jwtToken) {
        return jwtHelper.getUsername(jwtToken);
    }

    @Override
    public boolean isTokenExpired(String token) {
        return jwtHelper.isTokenExpired(token);
    }


    @Override
    public boolean shouldTokenRefresh(String token, String projectCode) {
        Date issueAt = jwtHelper.getIssuedAt(token);
        LocalDateTime issueTime = LocalDateTime.ofInstant(issueAt.toInstant(), ZoneId.systemDefault());
        return LocalDateTime.now().minusSeconds(gatewayProjectDto.getTokenRefreshInterval()).isAfter(issueTime);
    }
}
